import React, {FC, useEffect, useState} from 'react'
import {
	Form,
	Row,
	Col,
	Input,
	Select,
	Cascader,
	TreeSelect,
	Modal,
	Table,
	Pagination,
} from 'antd'
// import validator from 'validator';
import {getAllCitys} from '@/service/common/index'
import {FleetColums} from '../../fleet/constant'
import SearchForm from '@/components/SearchForm'
import {PageType, SoundEnum} from '../constant'
import {getFleetList, getSelectPage} from '@/service/customer/fleet'
import {TreeItem} from '../detail'
import styles from './index.less'

interface PersonalInformationType {
	personalInformationFrom: any
	pageType: string
	dirver: any
	dict: any
	detailRecord?: Record<string, string>
	orgList: TreeItem[]
}

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

// interface Item {
//   key: string;
//   name: string;
//   age: number;
//   address: string;
// }

type OtherParams = {
	requisitionName?: string
	requisitionOrgname?: string
	purchaserName?: string
	contractTypename?: string
	supplierName?: string
	supplierNo?: string
	startTime?: string
	finishTime?: string
}

// 城市
const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

// 申请部门与项目申请人
const deptAddUserNames = {
	label: 'name',
	value: 'id',
	key: 'id',
}

const personalInformation: FC<PersonalInformationType> = ({
	personalInformationFrom,
	pageType,
	dict,
	detailRecord,
	orgList,
	dirver,
}) => {
	const [visible, setVisible] = useState(false)
	const [fleetLoading, setFleetLoading] = useState(false)
	const [fleetTotal, SetFleetTotal] = useState(0)
	const [fleetPagination, setFleetPagination] = useState({
		current: 1,
		pageSize: 10,
	})
	const [fleetList, setFleetList] = useState<any[]>([])
	const [selectedRow, setSelectedRow] = useState<any>([])
	// 城市
	const [citysList, setCitysList] = useState<CityOption[]>([])
	const [otherParams, setOtherParams] = useState<OtherParams>()
	// 需求组织变化
	const onRequisitionOrgChange = (value: string, option: any) => {
		setOtherParams({...otherParams, requisitionOrgname: option[0]})
	}

	// 城市变化
	const onCitysChange = (value: any, selectedOptions: any) => {
		if (value) {
			personalInformationFrom.setFieldsValue({
				applyCityid: selectedOptions[selectedOptions.length - 1].value,
			})
		}
	}

	// 初始化-城市
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
	}, [])

	const FleetFormItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					key: 'fleetName',
					name: 'fleetName',
					label: '车队名称',
				},
				{
					type: 'input',
					key: 'captainName',
					name: 'captainName',
					label: '车队长名称',
				},
				{
					type: 'input',
					key: 'captainPhone',
					name: 'captainPhone',
					label: '车队长电话',
				},
			],
		},
	]

	const getFleetData = async (params?: any) => {
		const obj = {
			...params,
			current: fleetPagination.current,
			size: fleetPagination.pageSize,
		}
		setFleetLoading(true)
		const data = await getFleetList(obj).catch(() => {
			setFleetLoading(false)
		})
		if (data.code === 0) {
			setFleetList(data.data.records)
			SetFleetTotal(data.data.total || 0)
		}
		setFleetLoading(false)
	}

	const paginationChange = (current: number, pageSize: number) => {
		setFleetPagination({
			current,
			pageSize,
		})
	}

	// const setFleetId = async(fleetName:any) => {
	//   const res = await getSelectPage({fleetName})
	//   console.log(res)
	//   if(res.success && res.data) {
	//     personalInformationFrom.setFieldValue('captainName',res.data.captainName)
	//     personalInformationFrom.setFieldValue('fleetId',res.data.id)
	//   }
	// }

	const [data, setData] = useState<any>([])
	// const [value, setValue] = useState<string>();

	const handleSearch = async (fleetName: string) => {
		if (fleetName) {
			const res = await getSelectPage({fleetName})
			if (res.success && res.data.length) {
				setData(res.data)
			}
		} else {
			setData([])
		}
	}

	const handleChange = (id: string) => {
		const v = data.find((item: any) => item.id === id)
		if (v) {
			personalInformationFrom.setFieldValue('captainName', v.captainName)
			personalInformationFrom.setFieldValue('fleetId', v.id)
		}
	}
	// 回显表单
	const initForm = () => {
		const obj: Record<string, any> = {}
		if (
			(pageType === PageType.edit || pageType === PageType.detail) &&
			detailRecord
		) {
			obj.expressId = detailRecord.expressId
			obj.isDdOrder = String(detailRecord.isDdOrder)
			obj.usource = detailRecord.usource
			obj.ditchCode = detailRecord.ditchCode
			obj.tag = detailRecord.tag
			obj.status = detailRecord.status?.toString()
			obj.name = detailRecord.name
			obj.tel = detailRecord.tel
			obj.idNo = detailRecord.idNo
			obj.cityId = [detailRecord.provinceId, detailRecord.cityId]
			obj.groupOrgId = detailRecord.groupOrgId
			obj.gender = String(detailRecord.gender || '')
			obj.networkCarHistory = String(detailRecord.networkCarHistory || '')
			obj.education = detailRecord.education
			obj.workType = detailRecord.workType
			obj.hukouProvince = detailRecord.hukouProvince
				? detailRecord.hukouProvince.split(',').map(Number)
				: []
			obj.hukouDetail = detailRecord.hukouDetail
			obj.resideProvince = detailRecord.resideProvince
				? detailRecord.resideProvince.split(',').map(Number)
				: []
			obj.resideDetail = detailRecord.resideDetail
			obj.fleetName = detailRecord.fleetName
			obj.fleetAdminName = detailRecord.fleetAdminName
		} else if (pageType === PageType.add) {
			obj.status = '3'
			obj.isDdOrder = Number(dirver) === SoundEnum.yes ? '0' : '1'
		}
		personalInformationFrom.setFieldsValue(obj)
	}

	useEffect(() => {
		initForm()
	}, [detailRecord])

	useEffect(() => {
		if (!visible) return
		getFleetData()
	}, [fleetPagination.current, fleetPagination.pageSize, visible])

	return (
		<div className={styles.PersonalInformation}>
			<div className={styles.titleBox}>个人信息</div>
			<div className={styles.contentBox}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={personalInformationFrom}
					disabled={pageType === PageType.detail}>
					<Row>
						<Col span={8}>
							<Form.Item name="expressId" label="司机ID">
								<Input disabled />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item name="isDdOrder" label="司机类型">
								<Select
									disabled
									showSearch
									placeholder="请选择"
									options={[
										{label: '滴滴司机', value: '0'},
										{label: '非滴滴司机', value: '1'},
									]}
								/>
							</Form.Item>
						</Col>
						{pageType !== PageType.add && (
							<>
								<Col span={8}>
									<Form.Item
										name="usource"
										label="司机渠道来源">
										<Select
											disabled
											showSearch
											placeholder={
												pageType === PageType.detail
													? ''
													: '请选择'
											}
											options={(
												dict.driver_channel_source || []
											).map((item: any) => ({
												label: item.dictValue,
												value: item.dictKey,
											}))}
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="ditchCode"
										label="司机渠道代码">
										<Input
											disabled
											placeholder={
												pageType !== PageType.add
													? ''
													: '请输入'
											}
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item name="tag" label="司机标签">
										<Input
											disabled
											placeholder={
												pageType !== PageType.add
													? ''
													: '请输入'
											}
										/>
									</Form.Item>
								</Col>
							</>
						)}

						<Col span={8}>
							<Form.Item name="status" label="司机状态">
								<Select
									disabled
									showSearch
									placeholder={
										pageType !== PageType.add
											? ''
											: '请选择'
									}
									fieldNames={{
										label: 'dictValue',
										value: 'dictKey',
									}}
									options={dict.driver_status}
								/>
							</Form.Item>
						</Col>
						{pageType !== PageType.add && (
							<>
								<Col span={8}>
									<Form.Item
										name="fleetAdminName"
										label="车队长">
										<Input
											placeholder={
												pageType === PageType.detail
													? ''
													: ''
											}
											onClick={() => {
												setVisible(true)
											}}
											disabled
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="cityId"
										label="城市"
										rules={[{required: true}]}>
										<Cascader
											fieldNames={cityNames}
											options={citysList}
											placeholder="请选择"
											onChange={onCitysChange}
											disabled
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="groupOrgId"
										label="所属公司"
										rules={[{required: true}]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											placeholder="请选择"
											fieldNames={deptAddUserNames}
											treeDefaultExpandAll
											treeData={orgList}
											onChange={onRequisitionOrgChange}
											disabled
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="name"
										label="司机姓名"
										rules={[
											{required: true},
											{
												validator(rule, value) {
													if (
														value === undefined ||
														value.length === 0
													) {
														return Promise.resolve([
															'',
														])
													}
													return value.length > 40
														? Promise.reject(
																new Error(
																	'长度不能大于40',
																),
														  )
														: Promise.resolve([''])
												},
											},
										]}>
										{pageType === PageType.detail ? (
											<Input disabled />
										) : (
											<Input placeholder="请输入" />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="tel"
										label="司机手机号"
										rules={[
											{required: true},
											{
												pattern:
													/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
												message: '请输入正确的手机号',
											},
										]}>
										{pageType === PageType.detail ? (
											<Input disabled />
										) : (
											<Input placeholder="请输入" />
										)}
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="idNo"
										label="司机身份证号"
										rules={[{required: true}]}>
										{pageType === PageType.detail ? (
											<Input disabled />
										) : (
											<Input placeholder="请输入" />
										)}
									</Form.Item>
								</Col>
							</>
						)}

						{pageType === PageType.add && (
							<>
								<Col span={8}>
									<Form.Item
										name="name"
										label="司机姓名"
										rules={[
											{required: true},
											{
												validator(rule, value) {
													if (
														value === undefined ||
														value.length === 0
													) {
														return Promise.resolve([
															'',
														])
													}
													return value.length > 10
														? Promise.reject(
																new Error(
																	'长度不能大于10',
																),
														  )
														: Promise.resolve([''])
												},
											},
										]}>
										{/* {pageType === PageType.detail ? (
                      <Input disabled />
                    ) : (
                      <Input placeholder="请输入" />
                    )} */}
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="tel"
										label="司机手机号"
										rules={[
											{required: true},
											{
												pattern:
													/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
												message: '请输入正确的手机号',
											},
										]}>
										{/* {pageType === PageType.detail ? (
                      <Input disabled />
                    ) : (
                      <Input placeholder="请输入" />
                    )} */}
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="idNo"
										label="司机身份证号"
										rules={[{required: true}]}>
										{/* {pageType === PageType.detail ? (
                      <Input disabled />
                    ) : (
                      <Input placeholder="请输入" />
                    )} */}
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="cityId"
										label="城市"
										rules={[{required: true}]}>
										<Cascader
											fieldNames={cityNames}
											options={citysList}
											placeholder="请选择"
											onChange={onCitysChange}
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="groupOrgId"
										label="所属公司"
										rules={[{required: true}]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											placeholder="请选择"
											fieldNames={deptAddUserNames}
											treeDefaultExpandAll
											treeData={orgList}
											onChange={onRequisitionOrgChange}
										/>
									</Form.Item>
								</Col>
								<Col span={8}>{}</Col>
							</>
						)}
						<Col span={8}>
							<Form.Item name="gender" label="性别">
								<Select
									showSearch
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									options={(dict.sex || []).map(
										(item: any) => ({
											label: item.dictValue,
											value: item.dictKey,
										}),
									)}
								/>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								name="networkCarHistory"
								label="网约车从业经历">
								<Select
									showSearch
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									options={(
										dict.online_car_hailing_experience || []
									).map((item: any) => ({
										label: item.dictValue,
										value: item.dictKey,
									}))}
								/>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item name="education" label="教育水平">
								<Select
									showSearch
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									options={(dict.education || []).map(
										(item: any) => ({
											label: item.dictValue,
											value: item.dictKey,
										}),
									)}
								/>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item name="workType" label="工作经历">
								<Select
									showSearch
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									options={(dict.work_experience || []).map(
										(item: any) => ({
											label: item.dictValue,
											value: item.dictKey,
										}),
									)}
								/>
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="hukouProvince" label="户口所在地">
								<Cascader
									fieldNames={cityNames}
									options={citysList}
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									onChange={onCitysChange}
								/>
							</Form.Item>
						</Col>
						<Col span={10}>
							<div style={{paddingLeft: '10px'}}>
								{pageType === PageType.detail ? (
									<span className={styles.detailText}>
										{detailRecord &&
											detailRecord.hukouDetail}
									</span>
								) : (
									<Form.Item
										name="hukouDetail"
										rules={[
											{
												validator(rule, value) {
													if (
														value === undefined ||
														value.length === 0
													) {
														return Promise.resolve([
															'',
														])
													}
													return value.length > 40
														? Promise.reject(
																new Error(
																	'长度不能大于40',
																),
														  )
														: Promise.resolve([''])
												},
											},
										]}>
										<Input
											placeholder={
												pageType === PageType.detail
													? ''
													: '请输入详细地址'
											}
										/>
									</Form.Item>
								)}
							</div>
						</Col>
						<Col span={6}>
							<Form.Item name="resideProvince" label="现住址">
								<Cascader
									fieldNames={cityNames}
									options={citysList}
									placeholder={
										pageType === PageType.detail
											? ''
											: '请选择'
									}
									onChange={onCitysChange}
								/>
							</Form.Item>
						</Col>
						<Col span={10}>
							<div style={{paddingLeft: '10px'}}>
								{pageType === PageType.detail ? (
									<span className={styles.detailText}>
										{detailRecord &&
											detailRecord.resideDetail}
									</span>
								) : (
									<Form.Item
										name="resideDetail"
										rules={[
											{
												validator(rule, value) {
													if (
														value === undefined ||
														value.length === 0
													) {
														return Promise.resolve([
															'',
														])
													}
													return value.length > 40
														? Promise.reject(
																new Error(
																	'长度不能大于40',
																),
														  )
														: Promise.resolve([''])
												},
											},
										]}>
										<Input
											placeholder={
												pageType === PageType.detail
													? ''
													: '请输入详细地址'
											}
										/>
									</Form.Item>
								)}
							</div>
						</Col>
						<Col span={8} />
						{pageType !== PageType.add ? (
							<></>
						) : (
							<>
								<Col span={8}>
									<Form.Item
										name="fleetName"
										label="车队名称">
										{/* <Input onBlur={(e)=>{setFleetId(e.target.value)}}/> */}
										<Select
											showSearch
											// value={value}
											defaultActiveFirstOption={false}
											showArrow={false}
											filterOption={false}
											onSearch={handleSearch}
											onChange={handleChange}
											notFoundContent={null}
											options={(data || []).map(
												(d: any) => ({
													value: d.id,
													label: d.fleetName,
												}),
											)}
										/>
									</Form.Item>
								</Col>
								<Col span={8}>
									<Form.Item
										name="captainName"
										label="车队长姓名">
										<Input disabled />
									</Form.Item>
								</Col>
								<Col span={8} style={{display: 'none'}}>
									<Form.Item name="fleetId" label="fleetId">
										<Input disabled />
									</Form.Item>
								</Col>
							</>
						)}

						{/* {pageType !== PageType.add && (
              <>
                <Col span={8}>
                  <Form.Item name="fleetAdminName" label="车队长">
                    <Input disabled />
                  </Form.Item>
                </Col>
              </>
            )} */}
					</Row>
				</Form>
			</div>
			<Modal
				title="车队列表"
				open={visible}
				onCancel={() => {
					setVisible(false)
				}}
				width={1000}
				onOk={() => {
					setVisible(false)
					personalInformationFrom.setFieldsValue({
						fleetName: selectedRow.fleetName,
						captainName: selectedRow.captainName,
					})
				}}>
				<div className={styles.searchBox}>
					<SearchForm
						formLayout={{
							labelCol: {flex: '90px'},
							wrapperCol: {flex: '1'},
						}}
						formItems={FleetFormItems}
						onReset={() => {
							getFleetData()
						}}
						onFinish={(value) => {
							getFleetData(value)
						}}
					/>
				</div>
				<div className="content">
					<Table
						columns={FleetColums}
						rowKey="id"
						dataSource={fleetList}
						loading={fleetLoading}
						rowSelection={{
							type: 'radio',
							onChange: (
								selectedRowKeys: React.Key[],
								selectedRows: any[],
							) => {
								setSelectedRow(selectedRows[0])
							},
						}}
						scroll={{x: 1000, y: 400}}
						pagination={false}
					/>
					<div className="pagination">
						<Pagination
							pageSizeOptions={[10, 20]}
							defaultCurrent={1}
							current={fleetPagination.current}
							total={fleetTotal}
							showTotal={(total, range) =>
								`第  ${range[0]} - ${range[1]} 条 / 总共 ${total} 条`
							}
							showSizeChanger
							showQuickJumper
							onChange={paginationChange}
						/>
					</div>
				</div>
			</Modal>
		</div>
	)
}
export default personalInformation
